<template>
  <div class="userSearch">
    <a-input-search
      readOnly
      unselectable="on"
      v-model="leagueData"
      placeholder="请先选择团员"
      :loading="loading"
      @search="onSearchUser"
    >
      <a-button slot="enterButton" :disabled="disabled">选择团员</a-button>
    </a-input-search>
    <a-table
      v-if="showInfo && data.length"
      ref="info"
      size="middle"
      rowKey="id"
      :columns="columns"
      :dataSource="data"
      :pagination="false"
    >
    </a-table>
    <a-modal :title="title" :width="800" :visible="visible" @ok="handleOk" @cancel="handleCancel">
      <a-form ref="form">
        <a-form-item label="学工号">
          <a-input-search
            v-model="queryParam.stdNo"
            placeholder="输入学工号"
            :loading="loading"
            @search="onSearch"
            enter-button
          />
        </a-form-item>
      </a-form>

      <a-table
        ref="table"
        size="middle"
        rowKey="id"
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }"
        :pagination="ipagination"
        @change="handleTableChange"
      >
      </a-table>
    </a-modal>
  </div>
</template>

<script>
import { filterObj } from '@/utils/util'
import { postAction, getAction } from '@/api/manage'
export default {
  name: 'XSearchLeagueMember',
  props: {
    value: [String, Number],
    showInfo: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    param: Object
  },
  data() {
    return {
      title: '选择团员',
      loading: false,
      visible: false,
      error: '',
      errorTxt: '',
      leagueData: '',
      queryParam: {
        stdNo: ''
      },
      columns: [
        {
          title: '学号',
          align: 'center',
          dataIndex: 'stdNo'
        },
        {
          title: '姓名',
          align: 'center',
          dataIndex: 'realname'
        },
        {
          title: '学院',
          align: 'center',
          dataIndex: 'college'
        },
        {
          title: '专业',
          align: 'center',
          dataIndex: 'major'
        },
        {
          title: '年级',
          align: 'center',
          dataIndex: 'grade'
        },
        {
          title: '班级',
          align: 'center',
          dataIndex: 'clazz'
        }
      ],
      data: [],
      dataSource: [],
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      selectedRowKeys: [],
      selectionRows: [],
      selectUserIds: [],
      url: {
        user: '/leagueMem/list'
      }
    }
  },
  watch: {
    value: {
      handler(nv, ov) {
        if (nv && nv != ov) {
          this.initData()
        } else {
            this.dataSource = []
            this.searchReset()
            this.data = []
        }
      },
      immediate: true
    },
    "param.userId":{
        handler(nv,on){
            if(nv){
                this.initData()
            }
        },
        immediate:true
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    handleOk() {
      this.getSelectUserRows()
      this.data = this.selectUserRows
      this.$emit('change', this.selectUserIds)
      this.$emit('onchange', this.data)
      console.log(this.data)
      this.searchReset(0)
      this.visible = false
    },
    handleCancel() {
      this.visible = false
    },
    //获取选择用户信息
    getSelectUserRows() {
      let dataSource = this.dataSource
      let userIds = ''
      this.selectUserRows = []
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedRowKeys.includes(dataSource[i].id)) {
          this.selectUserRows.push(dataSource[i])
          userIds = userIds + ',' + dataSource[i].id
        }
      }
      this.selectUserIds = userIds.substring(1)
    },
    onSearchUser() {
      this.visible = true
    },
    onSearch() {
      this.loadData(1)
    },
    initData() {
      this.loading = true
      let values = this.value ? this.value.split(',') + '' : ''
      let obj = values ? { id: values } : {}
      let param = Object.assign(
        {
          pageNo: 1,
          pageSize: values.length
        },
        obj,
        this.param
      )
      getAction(this.url.user, param)
        .then(res => {
          if (res.success && res.result && res.result.records) {
            this.dataSource = res.result.records
            let selectedRowKeys = []
            let realNames = []
            res.result.records.forEach(user => {
              realNames.push(user['realname'])
              selectedRowKeys.push(user['id'])
            })
            this.selectedRowKeys = selectedRowKeys
            this.leagueData = realNames.join(',')
            this.getSelectUserRows()
            this.data = this.selectUserRows
          } else {
            this.data = []
            this.leagueData = ''
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    loadData(arg) {
      if (arg === 1) {
        this.ipagination.current = 1
      }
      this.loading = true
      let params = this.getQueryParams() //查询条件
      getAction(this.url.user, Object.assign({}, params, this.params))
        .then(res => {
          if (res.success) {
            this.dataSource = res.result.records
            this.ipagination.total = res.result.total
          } else {
            this.dataSource = []
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleTableChange(pagination, filters, sorter) {
      //TODO 筛选
      this.ipagination = pagination
      this.loadData()
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    searchReset(num) {
      let that = this
      if (num !== 0) {
        that.queryParam = {}
        that.loadData(1)
      }
      that.selectedRowKeys = []
      that.selectUserIds = []
    },
    getQueryParams() {
      let param = Object.assign({}, this.queryParam)
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    }
  }
}
</script>

<style scoped>
.userSearch {
}
</style>
